package leetcode_core.leetcode_1;

import java.util.LinkedList;
import java.util.List;

public class PancakeSort {
    private LinkedList<Integer> ans = new LinkedList<>();

    public List<Integer> pancakeSort(int[] arr) {
        sort(arr,arr.length);
        return ans;
    }
    //将前n块烧饼排序
    private void sort(int[] cakes,int n){
        //base-case
        if(n==1){
            return;
        }
        //寻找最大烧饼的索引
        int maxCake = 0;
        int maxCakeIndex = 0;
        for(int i = 0;i<n;i++){
            if(cakes[i] > maxCake){
                maxCakeIndex = i;
                maxCake = cakes[i];
            }
        }
        //第一次翻转,将最大烧饼翻到最上面
        reverse(cakes,0,maxCakeIndex);
        //记录这一次翻转
        ans.add(maxCakeIndex+1);
        //第二次翻转,将最大烧饼翻到最下面
        reverse(cakes,0,n-1);
        ans.add(n);
        sort(cakes,n-1);
    }
    private void reverse(int[] arr,int i,int j){
        while(i<j){
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;j--;
        }
    }
}
